package com.itjob.scott.student.dao.impl;

import java.util.ArrayList;
import java.util.List;

import javax.annotation.Resource;

import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.stereotype.Repository;

import com.itjob.scott.student.dao.StudentDao;
import com.itjob.scott.student.entity.StudentEntity;

@Repository
public class StudentDaoImpl implements StudentDao {
	
	@Resource
	private JdbcTemplate template;

	public int queryStudentByUsernameAndPassword(StudentEntity entity) {
		String sql = "select count(1) from sims_student_t where  user_name=? and password=?";
		return template.queryForObject(sql, Integer.class, new Object[]{entity.getUsername(),entity.getPassword()});
	}

	public int queryStudentByUsername(String username) {
		String sql = "select count(1) from sims_student_t where  user_name=?";
		return template.queryForObject(sql, Integer.class, new Object[]{username});
	}
	
	public int getNewStudentId(){
		String sql = "select sims_student_s.nextval from dual";
		return template.queryForObject(sql, Integer.class);
	}

	public void insertStudentEntity(StudentEntity entity) {
		String sql ="insert into sims_student_t values(?,?, ?, ?, ?, ?, ?)";
		template.update(sql, new Object[]{
				entity.getId(),
				entity.getUsername(),
				entity.getPassword(),
				entity.isGender(),
				entity.getBirthday(),
				entity.getEducation(),
				entity.getIntro(),
		});
	}
	
	
	public void insertStudentAndLanguageRelationship(StudentEntity entity){
		
		String[] languages = entity.getLanguages();
		
		List<Object[]> list = new ArrayList<Object[]>();
		for(int i = 0; i < languages.length; i++){
			String lang = languages[i];
			if(lang != null  && !lang.equals("")){
				Object[] obj=  new Object[]{entity.getId(),lang,};
				list.add(obj);
			}
		}
		
		//Initiating transaction commit
		String sql ="insert into sims_stu_lang_rel_t values(sims_stu_lang_rel_s.nextval,?,(select id from sims_language_t where language_key =?))";
		
		//Initiating transaction rollback
		//String sql ="insert into sims_stu_lang_rel_t values(sims_stu_lang_rel_s.nextval,?,(select id from sims_language_t where language_key =?));";
		
		template.batchUpdate(sql, list);
		
		/*for (int i = 0; i < languages.length; i++) {
			String lang = languages[i];
			if(lang != null  && !lang.equals("")){
				String sql ="insert into sims_stu_lang_rel_t values(sims_stu_lang_rel_s.nextval,?,(select id from sims_language_t where language_key =?))";
				template.update(sql, new Object[]{
						entity.getId(),
						lang,
				});
			}
		}*/
		
		
	}

}
